package main.database;

import com.mongodb.client.FindIterable;
import com.mongodb.client.MongoCollection;
import com.mongodb.client.MongoCursor;
import com.mongodb.client.model.Filters;
import main.GlobalConfig;
import main.TimeHelper;
import org.bson.Document;

import java.util.ArrayList;
import java.util.List;

public class MessageHelper {
    public static void addMessage(String fromId, String toId, String msg) {
        if (fromId.equals(toId)) return;

        MongoCollection<Document> collection = DatabaseMan.Instance().GetCollection(GlobalConfig.collectionNameOfMessage);

        if (AccountHelper.isExistFromUUID(fromId) && AccountHelper.isExistFromUUID(toId)) {
            Document document = new Document("fromid", fromId)
                    .append("toid", toId)
                    .append("message", msg)
                    .append("time", TimeHelper.getFormattedNowString())
                    .append("read", false);

            collection.insertOne(document);
        }
    }

    public static List<String[]> getReceivedMessageList(String uuid) {
        MongoCollection<Document> collection = DatabaseMan.Instance().GetCollection(GlobalConfig.collectionNameOfMessage);
        FindIterable<Document> documents = collection.find(Filters.eq("toid", uuid));
        MongoCursor<Document> cursor = documents.iterator();

        List<String[]> resultList = new ArrayList<>();
        while (cursor.hasNext()) {
            Document doc = cursor.next();

            String[] infos = new String[3];
            String fromId = doc.get("fromid").toString();
            String fromName = AccountHelper.getAccountInfoFromUUID(fromId);
            infos[0] = fromName;

            String time = doc.get("time").toString();
            infos[1] = time;

            String message = doc.get("message").toString();
            infos[2] = message;

            resultList.add(infos);
        }

        return resultList;
    }

    public static List<String[]> getSentMessageList(String uuid) {
        MongoCollection<Document> collection = DatabaseMan.Instance().GetCollection(GlobalConfig.collectionNameOfMessage);
        FindIterable<Document> documents = collection.find(Filters.eq("fromid", uuid));
        MongoCursor<Document> cursor = documents.iterator();

        List<String[]> resultList = new ArrayList<>();
        while(cursor.hasNext()) {
            Document doc = cursor.next();

            String[] infos = new String[3];
            String toId = doc.get("toid").toString();
            String toName = AccountHelper.getAccountInfoFromUUID(toId);
            infos[0] = toName;

            String time = doc.get("time").toString();
            infos[1] = time;

            String message = doc.get("message").toString();
            infos[2] = message;

            resultList.add(infos);
        }
        return resultList;
    }
}
